package com.jqr.activity.handlerlistviewroomdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.jqr.activity.handlerlistviewroomdemo.db.JqrjqDatabase;
import com.jqr.activity.handlerlistviewroomdemo.entity.User;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private  MyApplication myApplication;

    private ArrayAdapter<String> adapter;

    private List<String> userData;

    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myApplication=(MyApplication) getApplication();
        listView=findViewById(R.id.userListView);

        userData=new ArrayList<>();

        adapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,userData);

        listView.setAdapter(adapter);


        handler=new Handler(Looper.getMainLooper());

        new Thread(new Runnable() {
            @Override
            public void run() {
                myApplication.db.userDao().insert(new User("rose",21));
                myApplication.db.userDao().insert(new User("黄蓉",18));
                myApplication.db.userDao().insert(new User("郭靖",21));
                myApplication.db.userDao().insert(new User("穆念慈",19));
                List<User> users=myApplication.db.userDao().all();
                // 准备数据用于显示
                final List<String> userNames = new ArrayList<>();
                for (User u : users) {
                    userNames.add("Name: " + u.getUserName() + ", Age: " + u.getAge());
                }

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        userData.clear();
                        userData.addAll(userNames);
                        adapter.notifyDataSetChanged();
                    }
                });


            }
        }).start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null); //防止Handler 内存泄漏
    }
}